<template>
  <div id="container">
    <div id="terminal-container" class="xterm"></div>
  </div>
</template>

<script>
  import 'xterm/css/xterm.css'
  import { Terminal } from 'xterm'
  import { FitAddon } from 'xterm-addon-fit'

  import { WS } from '../assets/js/ws'

  export default {
    name: "Shell",
    data(){
      return {
        socketURI: '120.55.62.216:80/webshell',
        host:{
          hostIp: '',//IP
          hostPort: '',//端口号
          hostAccountUsername: '',//用户名
          hostAccountPassword: '',//密码
        },
      }
    },
    methods: {
      initTerm() {
        const term = new Terminal({
          cursorBlink: true, // 光标闪烁
          cursorStyle: "block", // 光标样式  null | 'block' | 'underline' | 'bar'
          scrollback: 800, //回滚
          tabStopWidth: 8, //制表宽度
          screenKeys: true,
          fontSize: 14,
        });
        const fitAddon = new FitAddon();
        term.loadAddon(fitAddon);
        term.open(document.getElementById('terminal-container'));
        fitAddon.fit();
        term.focus();

        this.term = term;
      },
      init(){
        let data = this.$data;
        this.initTerm();
        let term = this.term;
        let ws = new WS(data.host,data.socketURI);
        // //将ws与term向绑定
        // const attachAddon = new AttachAddon(this.ws);
        // term.loadAddon(attachAddon);
        this.ws = ws;
        data.isConnected = this.ws.initConnection({
          onError:function(errMsg){
            term.write('Error: ' + error + '\r\n');
          },
          onOpen:function(){
            term.write('Connecting... to ' + data.host.hostIp + '\r');
            ws.sendInitMsg(data.host);
          },
          onData:function(data){
            term.write(data);
          },
          onClose:function(){
            term.write("\rconnection closed");
          }
        }),
          term.onData(function(data){
            ws.sendOption(data);
          })
      }
    },
    mounted() {  //挂载不等于更新
      let data = this.$data;
      if(this.$route.params.hostIp!=null){
        data.host.hostIp = this.$route.params.hostIp;
        data.host.hostPort = this.$route.params.hostPort;
        data.host.hostAccountUsername = this.$route.params.hostAccountUsername;
        data.host.hostAccountPassword = this.$route.params.hostAccountPassword;
        this.init();
      }else{
        this.$message({
          message: 'shell初始化失败!',
          type: 'warning'
        })
      }
    },
    beforeDestroy() {
      this.ws._connection.close();  //在prototype下可以找到这个函数
      this.term.dispose();
    },
  }
</script>

<style scoped>

</style>
